package com.cyy.partner.controller;

import com.cyy.partner.common.Result;
import org.apache.tomcat.util.http.fileupload.impl.FileSizeLimitExceededException;
import org.springframework.util.ResourceUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import springfox.documentation.annotations.ApiIgnore;

import java.io.*;

/**
 * @Author: cyy
 * @Date: 2024/5/6
 * 图片上传处理
 */
@RestController
@ApiIgnore
public class FileUploadController {

//    @Value("${partner.path}")
//    private String basePath;

    /**
     * 上传图片
     * @param file
     * @return
     */
    @PostMapping("/upload")
    public Result<String> upload(MultipartFile file){
        String originalFilename = file.getOriginalFilename();
        //目录文件
        String fileDir = getFileDir();
        //文件名 = 当前时间+文件名
        String newFileName = System.currentTimeMillis() + originalFilename;
        try {
            //上传图片
            FileOutputStream out = new FileOutputStream(fileDir + "/" + newFileName);
            out.write(file.getBytes());
            out.flush();
            out.close();
        } catch (FileSizeLimitExceededException e){
            return Result.error("图片过大, 无法上传");
        }
        catch (Exception e) {
            throw new RuntimeException(e);
        }
        return Result.success(newFileName);
    }

    /**
     * 图片上传目录路径
     * @return
     */
    public String getFileDir(){
        //文件路径
        String path = "";
        try {
            path = ResourceUtils.getURL("classpath:").getPath();
            path = path + "static/img/";
        } catch (FileNotFoundException e) {
            throw new RuntimeException(e);
        }
        File filePath = new File(path);
        if(!filePath.exists()){
            filePath.mkdir();//目录不存在则新建
        }
        return path;
    }

}
